package io.renren.modules.mark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.mark.constant.ItemConstant;
import io.renren.modules.mark.dao.MarkDatasetDao;
import io.renren.modules.mark.dao.MarkItemDao;
import io.renren.modules.mark.entity.MarkDatasetEntity;
import io.renren.modules.mark.entity.MarkItemEntity;
import io.renren.modules.mark.form.ItemForm;
import io.renren.modules.mark.service.MarkItemService;
import io.renren.modules.mark.utils.IdWorker;
import io.renren.modules.oss.cloud.CloudStorageConfig;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysUserEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;


@Service("markItemService")
public class MarkItemServiceImpl extends ServiceImpl<MarkItemDao, MarkItemEntity> implements MarkItemService {

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private MarkItemDao markItemDao;

    @Autowired
    private MarkDatasetDao markDatasetDao;

    @Autowired
    private BucketManager manager;

    @Autowired
    private CloudStorageConfig config;

    @Autowired
    private IdWorker idWorker;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<MarkItemEntity> qw = new QueryWrapper<MarkItemEntity>();
        Integer datasetId = (Integer)params.get("datasetId");
        Integer state = (Integer) params.get("state");
        Long userId = (Long) params.get("userId");
        List<Integer> teams = (List<Integer>) params.get("teams");
        Integer min = (Integer) params.get("min");
        Integer max = (Integer) params.get("max");
        if(datasetId!=null){
            qw.eq("dataset_id",datasetId);
        }
        if(state!=null){
            if(state!=-1){
                qw.eq("state",state);
            }
        }
        if(userId!=null){
            qw.eq("user_id",userId);
        }
        if(teams!=null && teams.size()>0){
            qw.in("team_id",teams);
        }
        if(min!=null){
            qw.ge("state",min);
        }
        if(max!=null){
            qw.le("state",max);
        }
        //排序
        params.put("sidx","item_id");
        params.put("order","desc");
        qw.select("item_id, state, url, dataset_id, is_save");
        IPage<MarkItemEntity> page = this.page(
                new Query<MarkItemEntity>().getPage(params), qw);

        List<MarkItemEntity> records = page.getRecords();
        for (MarkItemEntity record : records) {
            if(record.getUserId()==null){
                continue;
            }
            SysUserEntity sysUserEntity =
                    sysUserDao.selectById(record.getUserId());
            if(sysUserEntity!=null){
                record.setUserName(sysUserEntity.getUsername());
            }
        }
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void deleteByIds(ItemForm itemForm) {
        List<String> strings = Arrays.asList(itemForm.getItemIds());
        QueryWrapper<MarkItemEntity> qw = new QueryWrapper<MarkItemEntity>();
        qw.in("url",strings);
        baseMapper.delete(qw);
        for (String string : strings) {
            try {
                string = string.replaceAll(config.getQiniuDomain()+"/","");
                Response delete = manager.delete(config.getQiniuBucketName(), string);
                int statusCode = delete.statusCode;
            }catch (Exception e){
                System.out.println(e.getMessage());
                throw  new RRException("删除图片失败");
            }
        }
        MarkDatasetEntity datasetEntity = markDatasetDao.selectById(itemForm.getDatasetId());
        MarkDatasetEntity entity = new MarkDatasetEntity();
        entity.setDatasetId(datasetEntity.getDatasetId());
        if(datasetEntity.getTotal()-strings.size()>0){
            entity.setTotal(datasetEntity.getTotal()-strings.size());
        }else{
            entity.setTotal(0);
        }
        markDatasetDao.updateById(entity);
    }

    @Override
    @Transactional
    public void saveAll(ItemForm itemForm) {
        int count = 0;
        for (String url : itemForm.getUrls()) {
            if(StringUtils.isBlank(url)){
                continue;
            }
            MarkItemEntity item = new MarkItemEntity();
            item.setUrl(url);
            item.setDatasetId(itemForm.getDatasetId());
            item.setItemId(idWorker.nextId());
            item.setState(ItemConstant.ItemType.BEGIN.getValue());
            item.setCreateTime(new Date());
            this.baseMapper.insert(item);
            count++;
        }
        MarkDatasetEntity datasetEntity = markDatasetDao.selectById(itemForm.getDatasetId());
        MarkDatasetEntity entity = new MarkDatasetEntity();
        entity.setDatasetId(datasetEntity.getDatasetId());
        entity.setTotal(datasetEntity.getTotal()+count);
        markDatasetDao.updateById(entity);
    }

    @Override
    @Transactional
    public synchronized void approve(MarkItemEntity markItem) {
        MarkItemEntity entity = new MarkItemEntity();
        entity.setItemId(markItem.getItemId());
        entity.setApproveId(markItem.getApproveId());
        entity.setState(markItem.getState());
        if(markItem.getLocation()!=null){
            entity.setLocation(markItem.getLocation());
        }
        entity.setUpdateTime(new Date());
        baseMapper.updateById(entity);
        MarkItemEntity item = baseMapper.selectById(markItem.getItemId());
        MarkDatasetEntity datasetEntity = markDatasetDao.selectById(item.getDatasetId());
        if(datasetEntity.getProcess()==null){
            datasetEntity.setProcess(0);
        }
        datasetEntity.setProcess(datasetEntity.getProcess()+1);
        //完成
        if(datasetEntity.getProcess()==datasetEntity.getTotal()){
            datasetEntity.setState(2);
        }
        markDatasetDao.updateById(datasetEntity);
    }

    @Override
    public List<Map<String, String>> selectRanking(String startTime, String endTime) {
        List<Map<String, String>> maps = markItemDao.selectRanking(startTime, endTime);
        return maps;
    }

}